;
(function ($, window, undefined) {
    'use strict';

    var $doc = $(document),
    Modernizr = window.Modernizr;

    $(document).ready(function() {
        $.fn.foundationAlerts           ? $doc.foundationAlerts() : null;
        $.fn.foundationButtons          ? $doc.foundationButtons() : null;
        $.fn.foundationAccordion        ? $doc.foundationAccordion() : null;
        $.fn.foundationNavigation       ? $doc.foundationNavigation() : null;
        $.fn.foundationTopBar           ? $doc.foundationTopBar() : null;
        $.fn.foundationCustomForms      ? $doc.foundationCustomForms() : null;
        $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null;
        $.fn.foundationTabs             ? $doc.foundationTabs({
            callback : $.foundation.customForms.appendCustomMarkup
        }) : null;
        $.fn.foundationTooltips         ? $doc.foundationTooltips() : null;
        $.fn.foundationMagellan         ? $doc.foundationMagellan() : null;
        $.fn.foundationClearing         ? $doc.foundationClearing() : null;

        $.fn.placeholder                ? $('input, textarea').placeholder() : null;
    });

    // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids
    // $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'});
    // $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'});
    // $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'});
    // $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'});

    // Hide address bar on mobile devices (except if #hash present, so we don't mess up deep linking).
    if (Modernizr.touch && !window.location.hash) {
        $(window).load(function () {
            setTimeout(function () {
                window.scrollTo(0, 1);
            }, 0);
        });
    }
       
    
    var config = {
        siteURL		: 'logicanica.com',	// Change this to your site
        searchSite	: false,
        type		: 'web',
        append		: false,
        perPage		: 8,			// A maximum of 8 is allowed by Google
        page		: 0				// The start page
    }
	
    // The small arrow that marks the active search icon:
    var arrow = $('<span>',{
        className:'arrow'
    }).appendTo('ul.icons');
	
    $('ul.icons li').click(function(){
        var el = $(this);
		
        if(el.hasClass('active')){
            // The icon is already active, exit
            return false;
        }
		
        el.siblings().removeClass('active');
        el.addClass('active');
		
        // Move the arrow below this icon
        arrow.stop().animate({
            left		: el.position().left,
            marginLeft	: (el.width()/2)-4
        });
		
        // Set the search type
        config.type = el.attr('data-searchType');
        $('#more').fadeOut();
    });

    // Marking the Search tutorialzine.com radio as active:
    $('#searchSite').click();	
	
    // Marking the web search icon as active:
    $('li.web').click();
	
    // Focusing the input text box:
    $('#s').focus();

    $('#searchForm').submit(function(){
        googleSearch();
        $('body,html').animate({
            scrollTop: 550
        }, 'slow'); 
        return false;
    });
	
    $('#searchSite,#searchWeb').change(function(){
        // Listening for a click on one of the radio buttons.
        // config.searchSite is either true or false.
		
        config.searchSite = this.id == 'searchSite';
    });
	
	
    function googleSearch(settings){
		
        // If no parameters are supplied to the function,
        // it takes its defaults from the config object above:
		
        settings = $.extend({},config,settings);
        settings.term = settings.term || $('#s').val();
		
        if(settings.searchSite){
            // Using the Google site:example.com to limit the search to a
            // specific domain:
            settings.term = 'site:'+settings.siteURL+' '+settings.term;
        }
		
        // URL of Google's AJAX search API
        var apiURL = 'http://ajax.googleapis.com/ajax/services/search/'+settings.type+'?v=1.0&callback=?';
        var resultsDiv = $('#main-content');
		
        $.getJSON(apiURL,{
            q:settings.term,
            rsz:settings.perPage,
            start:settings.page*settings.perPage
        },function(r){
			
            var results = r.responseData.results;
            $('#more').remove();
			
            if(results.length){
				
                // If results were returned, add them to a pageContainer div,
                // after which append them to the #resultsDiv:
				
                var pageContainer = $('<div>',{
                    className:'pageContainer'
                });
				
                for(var i=0;i<results.length;i++){
                    // Creating a new result object and firing its toString method:
                    pageContainer.append(new result(results[i]) + '');
                }
				
                if(!settings.append){
                    // This is executed when running a new search, 
                    // instead of clicking on the More button:
                    resultsDiv.empty();
                }
				
                pageContainer.append('<div class="clear"></div>')
                .hide().appendTo(resultsDiv)
                .fadeIn('slow');
				
                var cursor = r.responseData.cursor;
				
                // Checking if there are more pages with results, 
                // and deciding whether to show the More button:
				
                if( +cursor.estimatedResultCount > (settings.page+1)*settings.perPage){
                    $('<div>',{
                        id:'more'
                    }).appendTo(resultsDiv).click(function(){
                        googleSearch({
                            append:true,
                            page:settings.page+1
                        });
                        $(this).fadeOut();
                    });
                }
            }
            else {
				
                // No results were found for this search.
				
                resultsDiv.empty();
                $('<p>',{
                    className:'notFound',
                    html:'No Results Were Found!'
                }).hide().appendTo(resultsDiv).fadeIn();
            }
        });
    }
	
    function result(r){
		
        // This is class definition. Object of this class are created for
        // each result. The markup is generated by the .toString() method.
		
        var arr = [];
		
        // GsearchResultClass is passed by the google API
        switch(r.GsearchResultClass){

            case 'GwebSearch':
                arr = [
                '<div class="webResult">',
                '<h2><a href="',r.unescapedUrl,'" target="_blank">',r.title,'</a></h2>',
                '<p>',r.content,'</p>',
                '<a href="',r.unescapedUrl,'" target="_blank">',r.visibleUrl,'</a>',
                '</div>'
                ];
                break;
            case 'GimageSearch':
                arr = [
                '<div class="imageResult">',
                '<a target="_blank" href="',r.unescapedUrl,'" title="',r.titleNoFormatting,'" class="pic" style="width:',r.tbWidth,'px;height:',r.tbHeight,'px;">',
                '<img src="',r.tbUrl,'" width="',r.tbWidth,'" height="',r.tbHeight,'" /></a>',
                '<div class="clear"></div>','<a href="',r.originalContextUrl,'" target="_blank">',r.visibleUrl,'</a>',
                '</div>'
                ];
                break;
            case 'GvideoSearch':
                arr = [
                '<div class="imageResult">',
                '<a target="_blank" href="',r.url,'" title="',r.titleNoFormatting,'" class="pic" style="width:150px;height:auto;">',
                '<img src="',r.tbUrl,'" width="100%" /></a>',
                '<div class="clear"></div>','<a href="',r.originalContextUrl,'" target="_blank">',r.publisher,'</a>',
                '</div>'
                ];
                break;
            case 'GnewsSearch':
                arr = [
                '<div class="webResult">',
                '<h2><a href="',r.unescapedUrl,'" target="_blank">',r.title,'</a></h2>',
                '<p>',r.content,'</p>',
                '<a href="',r.unescapedUrl,'" target="_blank">',r.publisher,'</a>',
                '</div>'
                ];
                break;
        }
		
        // The toString method.
        this.toString = function(){
            return arr.join('');
        }
    }
        
})(jQuery, this);
$(function() {
    /* this is the index of the last clicked picture */
    var current = -1;
    /* number of pictures */
    var totalpictures = $('#content img').size();
    /* speed to animate the panel and the thumbs wrapper */
    var speed 	= 500;
				
    /* show the content */
    $('#content').show();
				
    /*
                when the user resizes the browser window,
                the size of the picture being viewed is recalculated;
                 */
    $(window).bind('resize', function() {
        var $picture = $('#wrapper').find('img');
        resize($picture);
    });
               
    /*
                when hovering a thumb, animate it's opacity
                for a cool effect;
                when clicking on it, we load the corresponding large image;
                the source of the large image is stored as 
                the "alt" attribute of the thumb image
                 */
    $('#content > img').hover(function () {
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'1.0'
        },200);
    },function () {
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'0.4'
        },200);
    }).bind('click',function(){
        var $this   = $(this);
                    
        /* shows the loading icon */
        $('#loading').show();
                    
        $('<img/>').load(function(){
            $('#loading').hide();
                        
            if($('#wrapper').find('img').length) return;
            current 	= $this.index();
            var $theImage   = $(this);
            /*
                        After it's loaded we hide the loading icon
                        and resize the image, given the window size;
                        then we append the image to the wrapper
                        */
                        
            resize($theImage);

            $('#wrapper').append($theImage);
            /* make its opacity animate */
            $theImage.fadeIn(800);
                        
            /* and finally slide up the panel */
            $('#panel').animate({
                'height':'100%'
            },speed,function(){
                /*
                            if the picture has a description,
                            it's stored in the title attribute of the thumb;
                            show it if it's not empty
                             */
                var title = $this.attr('title');
                if(title != '') 
                    $('#description').html(title).show();
                else 
                    $('#description').empty().hide();
                            
                /*
                            if our picture is the first one,
                            don't show the "previous button"
                            for the slideshow navigation;
                            if our picture is the last one,
                            don't show the "next button"
                            for the slideshow navigation
                             */
                if(current==0)
                    $('#prev').hide();
                else
                    $('#prev').fadeIn();
                if(current==parseInt(totalpictures-1))
                    $('#next').hide();
                else
                    $('#next').fadeIn();
                /*
                            we set the z-index and height of the thumbs wrapper 
                            to 0, because we want to slide it up afterwards,
                            when the user clicks the large image
                             */
                $('#thumbsWrapper').css({
                    'z-index':'0',
                    'height':'0px'
                });
            });
        }).attr('src', $this.attr('alt'));
    });

    /*
                when hovering a large image,
                we want to slide up the thumbs wrapper again,
                and reset the panel (like it was initially);
                this includes removing the large image element
                 */
    $('#wrapper > img').live('click',function(){
        $this = $(this);
        $('#description').empty().hide();
                    
        $('#thumbsWrapper').css('z-index','10')
        .stop()
        .animate({
            'height':'100%'
        },speed,function(){
            var $theWrapper = $(this);
            $('#panel').css('height','0px');
            $theWrapper.css('z-index','0');
            /* 
                        remove the large image element
                        and the navigation buttons
                         */
            $this.remove();
            $('#prev').hide();
            $('#next').hide();
        });
    });

    /*
                when we are viewing a large image,
                if we navigate to the right/left we need to know
                which image is the corresponding neighbour.
                we know the index of the current picture (current),
                so we can easily get to the neighbour:
                 */
    $('#next').bind('click',function(){
        var $this           = $(this);
        var $nextimage 		= $('#content img:nth-child('+parseInt(current+2)+')');
        navigate($nextimage,'right');
    });
    $('#prev').bind('click',function(){
        var $this           = $(this);
        var $previmage 		= $('#content img:nth-child('+parseInt(current)+')');
        navigate($previmage,'left');
    });

    /*
                given the next or previous image to show,
                and the direction, it loads a new image in the panel.
                 */
    function navigate($nextimage,dir){
        /*
                    if we are at the end/beginning
                    then there's no next/previous
                     */
        if(dir=='left' && current==0)
            return;
        if(dir=='right' && current==parseInt(totalpictures-1))
            return;
        $('#loading').show();
        $('<img/>').load(function(){
            var $theImage = $(this);
            $('#loading').hide();
            $('#description').empty().fadeOut();
                         
            $('#wrapper img').stop().fadeOut(500,function(){
                var $this = $(this);
							
                $this.remove();
                resize($theImage);
                            
                $('#wrapper').append($theImage.show());
                $theImage.stop().fadeIn(800);

                var title = $nextimage.attr('title');
                if(title != ''){
                    $('#description').html(title).show();
                }
                else
                    $('#description').empty().hide();

                if(current==0)
                    $('#prev').hide();
                else
                    $('#prev').show();
                if(current==parseInt(totalpictures-1))
                    $('#next').hide();
                else
                    $('#next').show();
            });
            /*
                        increase or decrease the current variable
                         */
            if(dir=='right')
                ++current;
            else if(dir=='left')
                --current;
        }).attr('src', $nextimage.attr('alt'));
    }

    /*
                resizes an image given the window size,
                considering the margin values
                 */
    function resize($image){
        var windowH      = $(window).height()-100;
        var windowW      = $(window).width()-80;
        var theImage     = new Image();
        
        var imgwidth     = 800;
        var imgheight    = 600;
        //console.log($image);
        
        var $img = $image;
	if ($img.prop('naturalWidth') == undefined) {
		var $tmpImg = $('<img/>').attr('src', $img.attr('src'));
		$img.prop('naturalWidth', $tmpImg[0].width);
		$img.prop('naturalHeight', $tmpImg[0].height);
	}
	imgwidth = $img.prop('naturalWidth');
        imgheight= $img.prop('naturalHeight');

        if((imgwidth > windowW)||(imgheight > windowH)){
            if(imgwidth > imgheight){
                var newwidth = windowW;
                var ratio = imgwidth / windowW;
                var newheight = imgheight / ratio;
                theImage.height = newheight;
                theImage.width= newwidth;
                if(newheight>windowH){
                    var newnewheight = windowH;
                    var newratio = newheight/windowH;
                    var newnewwidth =newwidth/newratio;
                    theImage.width = newnewwidth;
                    theImage.height= newnewheight;
                }
            }
            else{
                var newheight = windowH;
                var ratio = imgheight / windowH;
                var newwidth = imgwidth / ratio;
                theImage.height = newheight;
                theImage.width= newwidth;
                if(newwidth>windowW){
                    var newnewwidth = windowW;
                    var newratio = newwidth/windowW;
                    var newnewheight =newheight/newratio;
                    theImage.height = newnewheight;
                    theImage.width= newnewwidth;
                }
            }
        }
        $image.css({
            'width':theImage.width+'px',
            'height':theImage.height+'px'
        });
    }
});